<template>
  <div class="theme-toggle-container">
    <div class="theme-header">
      <h3>主题设置</h3>
      <p>{{ currentThemeMessage }}</p>
    </div>
    
    <!-- 主题模式选择 -->
    <div class="theme-modes">
      <button 
        class="mode-button"
        :class="{ active: themeMode === 'auto' }"
        @click="setThemeMode('auto')"
      >
        <div class="mode-icon">🌓</div>
        <div class="mode-text">
          <div class="mode-title">自动</div>
          <div class="mode-description">根据时间自动切换</div>
        </div>
      </button>
      
      <button 
        class="mode-button"
        :class="{ active: themeMode === 'dark' }"
        @click="setThemeMode('dark')"
      >
        <div class="mode-icon">🌙</div>
        <div class="mode-text">
          <div class="mode-title">深色模式</div>
          <div class="mode-description">星空背景，适合夜间使用</div>
        </div>
      </button>
      
      <button 
        class="mode-button"
        :class="{ active: themeMode === 'light' }"
        @click="setThemeMode('light')"
      >
        <div class="mode-icon">☀️</div>
        <div class="mode-text">
          <div class="mode-title">浅色模式</div>
          <div class="mode-description">明亮背景，适合白天使用</div>
        </div>
      </button>
    </div>
    
    <!-- 自动模式时间设置 -->
    <div v-if="themeMode === 'auto'" class="auto-settings">
      <h4>自动切换时间</h4>
      
      <div class="time-settings">
        <div class="time-setting">
          <label>日出时间 (切换为浅色)</label>
          <input 
            type="time" 
            v-model="sunriseTime" 
            @change="updateAutoThemeTimes"
          >
        </div>
        
        <div class="time-setting">
          <label>日落时间 (切换为深色)</label>
          <input 
            type="time" 
            v-model="sunsetTime" 
            @change="updateAutoThemeTimes"
          >
        </div>
      </div>
      
      <div class="next-theme-change">
        <div class="change-icon">🔄</div>
        <div class="change-text">
          <div class="change-title">下次主题切换</div>
          <div class="change-time">{{ nextThemeChangeTime }}</div>
        </div>
      </div>
    </div>
    
    <!-- 主题预览 -->
    <div class="theme-preview">
      <h4>主题预览</h4>
      
      <div class="preview-container">
        <div 
          class="preview-card dark-preview"
          :class="{ active: isDarkThemeActive }"
        >
          <div class="preview-header">
            <div class="preview-icon">🌙</div>
            <div class="preview-title">深色模式</div>
          </div>
          <div class="preview-content">
            <div class="preview-text">星空背景设计，减少眼部疲劳</div>
            <div class="preview-elements">
              <div class="preview-button">主要按钮</div>
              <div class="preview-input">输入框示例</div>
            </div>
          </div>
        </div>
        
        <div 
          class="preview-card light-preview"
          :class="{ active: isLightThemeActive }"
        >
          <div class="preview-header">
            <div class="preview-icon">☀️</div>
            <div class="preview-title">浅色模式</div>
          </div>
          <div class="preview-content">
            <div class="preview-text">明亮背景设计，提升可读性</div>
            <div class="preview-elements">
              <div class="preview-button">主要按钮</div>
              <div class="preview-input">输入框示例</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 主题自定义选项 -->
    <div class="theme-customization">
      <h4>主题自定义</h4>
      
      <div class="customization-options">
        <div class="option-group">
          <label>动画效果</label>
          <div class="toggle-switch">
            <input 
              type="checkbox" 
              id="animations-toggle" 
              v-model="animationsEnabled"
              @change="toggleAnimations"
            >
            <label for="animations-toggle" class="switch-slider"></label>
          </div>
        </div>
        
        <div class="option-group">
          <label>星空密度</label>
          <div class="slider-container">
            <input 
              type="range" 
              min="1" 
              max="5" 
              v-model.number="starDensity"
              @input="updateStarDensity"
              class="slider"
            >
            <span class="slider-value">{{ starDensity }}</span>
          </div>
        </div>
        
        <div class="option-group">
          <label>主题色调</label>
          <div class="color-picker">
            <button 
              v-for="color in themeColors" 
              :key="color.name"
              class="color-option"
              :class="{ active: selectedColor === color.name }"
              :style="{ backgroundColor: color.value }"
              @click="selectThemeColor(color.name)"
            >
              <span v-if="selectedColor === color.name" class="check-mark">✓</span>
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 主题应用状态 -->
    <div class="theme-status">
      <div class="status-content">
        <div class="status-icon">{{ themeStatusIcon }}</div>
        <div class="status-text">{{ themeStatusText }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'

export default {
  name: 'ThemeToggle',
  emits: ['theme-changed'],
  setup(props, { emit }) {
    // 主题设置
    const themeMode = ref('auto') // auto, dark, light
    const currentTheme = ref('dark') // 当前实际应用的主题
    const animationsEnabled = ref(true)
    const starDensity = ref(3)
    const selectedColor = ref('blue')
    
    // 自动模式时间设置
    const sunriseTime = ref('06:00')
    const sunsetTime = ref('18:00')
    
    // 计时器引用
    let themeCheckTimer = null
    
    // 主题颜色选项
    const themeColors = [
      { name: 'blue', value: '#5588ff', label: '蓝色' },
      { name: 'purple', value: '#9b59b6', label: '紫色' },
      { name: 'teal', value: '#1dd1a1', label: '青色' },
      { name: 'amber', value: '#f39c12', label: '琥珀色' },
      { name: 'pink', value: '#e91e63', label: '粉色' }
    ]
    
    // 组件挂载时初始化
    onMounted(() => {
      // 从本地存储加载设置
      loadThemeSettings()
      
      // 初始应用主题
      applyTheme()
      
      // 如果是自动模式，启动计时器
      if (themeMode.value === 'auto') {
        startThemeCheckTimer()
      }
    })
    
    // 组件卸载时清理
    onUnmounted(() => {
      if (themeCheckTimer) {
        clearInterval(themeCheckTimer)
      }
    })
    
    // 从本地存储加载设置
    const loadThemeSettings = () => {
      const savedMode = localStorage.getItem('themeMode')
      if (savedMode) themeMode.value = savedMode
      
      const savedAnimations = localStorage.getItem('animationsEnabled')
      if (savedAnimations !== null) animationsEnabled.value = savedAnimations === 'true'
      
      const savedDensity = localStorage.getItem('starDensity')
      if (savedDensity) starDensity.value = parseInt(savedDensity)
      
      const savedColor = localStorage.getItem('themeColor')
      if (savedColor) selectedColor.value = savedColor
      
      const savedSunrise = localStorage.getItem('sunriseTime')
      if (savedSunrise) sunriseTime.value = savedSunrise
      
      const savedSunset = localStorage.getItem('sunsetTime')
      if (savedSunset) sunsetTime.value = savedSunset
    }
    
    // 保存设置到本地存储
    const saveThemeSettings = () => {
      localStorage.setItem('themeMode', themeMode.value)
      localStorage.setItem('animationsEnabled', animationsEnabled.value.toString())
      localStorage.setItem('starDensity', starDensity.value.toString())
      localStorage.setItem('themeColor', selectedColor.value)
      localStorage.setItem('sunriseTime', sunriseTime.value)
      localStorage.setItem('sunsetTime', sunsetTime.value)
    }
    
    // 设置主题模式
    const setThemeMode = (mode) => {
      themeMode.value = mode
      
      // 清理之前的计时器
      if (themeCheckTimer) {
        clearInterval(themeCheckTimer)
      }
      
      // 如果是自动模式，启动计时器
      if (mode === 'auto') {
        startThemeCheckTimer()
      } else {
        // 手动模式直接应用主题
        currentTheme.value = mode
        applyTheme()
      }
      
      saveThemeSettings()
      emit('theme-changed', { mode, current: currentTheme.value })
    }
    
    // 启动主题检查计时器
    const startThemeCheckTimer = () => {
      // 立即检查一次
      checkAutoTheme()
      
      // 每分钟检查一次
      themeCheckTimer = setInterval(() => {
        checkAutoTheme()
      }, 60000)
    }
    
    // 检查并应用自动主题
    const checkAutoTheme = () => {
      const now = new Date()
      const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
      
      let targetTheme = 'dark' // 默认深色
      
      // 比较时间来确定主题
      if (currentTime >= sunriseTime.value && currentTime < sunsetTime.value) {
        targetTheme = 'light'
      }
      
      // 如果主题变化了，应用新主题
      if (currentTheme.value !== targetTheme) {
        currentTheme.value = targetTheme
        applyTheme()
        emit('theme-changed', { mode: 'auto', current: targetTheme })
      }
    }
    
    // 应用主题到文档
    const applyTheme = () => {
      // 移除所有主题类
      document.documentElement.classList.remove('theme-dark', 'theme-light')
      
      // 添加当前主题类
      document.documentElement.classList.add(`theme-${currentTheme.value}`)
      
      // 设置CSS变量
      const root = document.documentElement
      
      if (currentTheme.value === 'dark') {
        root.style.setProperty('--bg-primary', '#050518')
        root.style.setProperty('--bg-secondary', '#0a0a2a')
        root.style.setProperty('--bg-card', 'rgba(10, 10, 42, 0.85)')
        root.style.setProperty('--text-primary', '#ffffff')
        root.style.setProperty('--text-secondary', 'rgba(255, 255, 255, 0.6)')
        root.style.setProperty('--border-color', 'rgba(85, 136, 255, 0.2)')
        root.style.setProperty('--shadow-color', 'rgba(0, 0, 0, 0.5)')
      } else {
        root.style.setProperty('--bg-primary', '#f0f2f5')
        root.style.setProperty('--bg-secondary', '#ffffff')
        root.style.setProperty('--bg-card', 'rgba(255, 255, 255, 0.95)')
        root.style.setProperty('--text-primary', '#1a1a2e')
        root.style.setProperty('--text-secondary', 'rgba(26, 26, 46, 0.6)')
        root.style.setProperty('--border-color', 'rgba(85, 136, 255, 0.3)')
        root.style.setProperty('--shadow-color', 'rgba(0, 0, 0, 0.1)')
      }
      
      // 应用主题色调
      const selectedColorObj = themeColors.find(color => color.name === selectedColor.value)
      if (selectedColorObj) {
        root.style.setProperty('--accent-color', selectedColorObj.value)
      }
      
      // 应用动画设置
      if (!animationsEnabled.value) {
        root.style.setProperty('animation', 'none')
        root.style.setProperty('transition', 'none')
      } else {
        root.style.removeProperty('animation')
        root.style.removeProperty('transition')
      }
    }
    
    // 更新自动主题时间
    const updateAutoThemeTimes = () => {
      saveThemeSettings()
      checkAutoTheme() // 立即重新检查
    }
    
    // 切换动画效果
    const toggleAnimations = () => {
      saveThemeSettings()
      applyTheme()
    }
    
    // 更新星空密度
    const updateStarDensity = () => {
      saveThemeSettings()
      // 这里可以通过事件通知父组件更新星空密度
      emit('theme-changed', { 
        mode: themeMode.value, 
        current: currentTheme.value,
        starDensity: starDensity.value
      })
    }
    
    // 选择主题色调
    const selectThemeColor = (colorName) => {
      selectedColor.value = colorName
      saveThemeSettings()
      applyTheme()
    }
    
    // 计算属性
    const currentThemeMessage = computed(() => {
      const messages = {
        auto: '根据日出日落时间自动切换主题',
        dark: '当前使用深色模式，适合夜间使用',
        light: '当前使用浅色模式，适合白天使用'
      }
      return messages[themeMode.value]
    })
    
    const isDarkThemeActive = computed(() => {
      return currentTheme.value === 'dark'
    })
    
    const isLightThemeActive = computed(() => {
      return currentTheme.value === 'light'
    })
    
    const nextThemeChangeTime = computed(() => {
      if (themeMode.value !== 'auto') return ''
      
      const now = new Date()
      const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
      
      // 确定下次切换时间
      let nextTime = currentTime >= sunriseTime.value && currentTime < sunsetTime.value 
        ? sunsetTime.value 
        : sunriseTime.value
      
      // 格式化显示
      const nextTimeObj = new Date()
      const [hours, minutes] = nextTime.split(':')
      nextTimeObj.setHours(parseInt(hours), parseInt(minutes), 0, 0)
      
      // 如果是第二天的时间
      if (themeMode.value === 'auto') {
        if (currentTime >= sunsetTime.value && nextTime === sunriseTime.value) {
          nextTimeObj.setDate(nextTimeObj.getDate() + 1)
        }
      }
      
      return nextTimeObj.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    })
    
    const themeStatusIcon = computed(() => {
      const icons = {
        dark: '🌙',
        light: '☀️'
      }
      return icons[currentTheme.value] || '🌓'
    })
    
    const themeStatusText = computed(() => {
      const statuses = {
        dark: '深色模式已启用',
        light: '浅色模式已启用'
      }
      return statuses[currentTheme.value] || '主题设置已保存'
    })
    
    return {
      themeMode,
      currentTheme,
      animationsEnabled,
      starDensity,
      selectedColor,
      sunriseTime,
      sunsetTime,
      themeColors,
      currentThemeMessage,
      isDarkThemeActive,
      isLightThemeActive,
      nextThemeChangeTime,
      themeStatusIcon,
      themeStatusText,
      setThemeMode,
      updateAutoThemeTimes,
      toggleAnimations,
      updateStarDensity,
      selectThemeColor
    }
  }
}
</script>

<style scoped>
.theme-toggle-container {
  background: var(--bg-card, rgba(10, 10, 42, 0.85));
  border-radius: 16px;
  padding: 24px;
  border: 1px solid var(--border-color, rgba(85, 136, 255, 0.2));
  box-shadow: 0 10px 30px var(--shadow-color, rgba(0, 0, 0, 0.3));
  color: var(--text-primary, #ffffff);
}

.theme-header {
  text-align: center;
  margin-bottom: 24px;
}

.theme-header h3 {
  margin: 0 0 8px;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary, #ffffff);
}

.theme-header p {
  margin: 0;
  font-size: 14px;
  color: var(--text-secondary, rgba(255, 255, 255, 0.6));
}

/* 主题模式选择 */
.theme-modes {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 24px;
}

.mode-button {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: transparent;
  border: 2px solid var(--border-color, rgba(85, 136, 255, 0.2));
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: var(--text-primary, #ffffff);
}

.mode-button:hover {
  border-color: var(--accent-color, #5588ff);
  background: rgba(85, 136, 255, 0.05);
  transform: translateY(-2px);
}

.mode-button.active {
  border-color: var(--accent-color, #5588ff);
  background: rgba(85, 136, 255, 0.1);
  box-shadow: 0 4px 12px rgba(85, 136, 255, 0.2);
}

.mode-icon {
  font-size: 32px;
  flex-shrink: 0;
}

.mode-text {
  flex: 1;
}

.mode-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
  color: var(--text-primary, #ffffff);
}

.mode-description {
  font-size: 13px;
  color: var(--text-secondary, rgba(255, 255, 255, 0.6));
}

/* 自动设置 */
.auto-settings {
  background: rgba(85, 136, 255, 0.05);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  border: 1px solid var(--border-color, rgba(85, 136, 255, 0.2));
}

.auto-settings h4 {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary, #ffffff);
}

.time-settings {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.time-setting {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.time-setting label {
  font-size: 14px;
  color: var(--text-secondary, rgba(255, 255, 255, 0.6));
}

.time-setting input[type="time"] {
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid var(--border-color, rgba(85, 136, 255, 0.2));
  border-radius: 8px;
  color: var(--text-primary, #ffffff);
  font-size: 16px;
}

.next-theme-change {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: rgba(85, 136, 255, 0.1);
  border-radius: 8px;
}

.change-icon {
  font-size: 24px;
  flex-shrink: 0;
}

.change-title {
  font-size: 13px;
  color: var(--text-secondary, rgba(255, 255, 255, 0.6));
  margin-bottom: 2px;
}

.change-time {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary, #ffffff);
}

/* 主题预览 */
.theme-preview {
  margin-bottom: 24px;
}

.theme-preview h4 {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary, #ffffff);
}

.preview-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.preview-card {
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.preview-card.active {
  border-color: var(--accent-color, #5588ff);
  box-shadow: 0 4px 16px rgba(85, 136, 255, 0.3);
}

.dark-preview {
  background: linear-gradient(135deg, #050518, #0a0a2a);
  color: #ffffff;
}

.light-preview {
  background: linear-gradient(135deg, #f0f2f5, #ffffff);
  color: #1a1a2e;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.light-preview .preview-header {
  border-bottom-color: rgba(0, 0, 0, 0.1);
}

.preview-icon {
  font-size: 24px;
}

.preview-title {
  font-size: 16px;
  font-weight: 600;
}

.preview-content {
  padding: 16px;
}

.preview-text {
  font-size: 13px;
  margin-bottom: 16px;
  opacity: 0.8;
}

.preview-elements {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-button {
  padding: 8px 16px;
  border-radius: 6px;
  background: var(--accent-color, #5588ff);
  color: #ffffff;
  text-align: center;
  font-size: 13px;
  font-weight: 600;
}

.preview-input {
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  font-size: 13px;
  opacity: 0.8;
}

.light-preview .preview-input {
  border-color: rgba(0, 0, 0, 0.2);
}

/* 主题自定义 */
.theme-customization {
  margin-bottom: 24px;
}

.theme-customization h4 {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary, #ffffff);
}

.customization-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.option-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.option-group label {
  font-size: 14px;
  color: var(--text-primary, #ffffff);
}

/* 切换开关 */
.toggle-switch {
  position: relative;
  width: 50px;
  height: 24px;
}

.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.switch-slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.2);
  transition: 0.4s;
  border-radius: 24px;
}

.switch-slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: 0.4s;
  border-radius: 50%;
}

input:checked + .switch-slider {
  background-color: var(--accent-color, #5588ff);
}

input:checked + .switch-slider:before {
  transform: translateX(26px);
}

/* 滑块 */
.slider-container {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  max-width: 200px;
}

.slider {
  flex: 1;
  -webkit-appearance: none;
  height: 6px;
  border-radius: 3px;
  background: rgba(255, 255, 255, 0.2);
  outline: none;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: var(--accent-color, #5588ff);
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(85, 136, 255, 0.3);
}

.slider::-moz-range-thumb {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: var(--accent-color, #5588ff);
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(85, 136, 255, 0.3);
  border: none;
}

.slider-value {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary, #ffffff);
  min-width: 20px;
  text-align: center;
}

/* 颜色选择器 */
.color-picker {
  display: flex;
  gap: 8px;
}

.color-option {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.color-option:hover {
  transform: scale(1.1);
}

.color-option.active {
  border-color: var(--text-primary, #ffffff);
  box-shadow: 0 0 0 3px rgba(85, 136, 255, 0.3);
}

.check-mark {
  color: #ffffff;
  font-size: 16px;
  font-weight: bold;
  text-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
}

/* 主题状态 */
.theme-status {
  text-align: center;
  padding: 16px;
  background: rgba(85, 136, 255, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(85, 136, 255, 0.2);
}

.status-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.status-icon {
  font-size: 24px;
}

.status-text {
  font-size: 14px;
  color: var(--text-secondary, rgba(255, 255, 255, 0.6));
}

/* 响应式设计 */
@media (max-width: 768px) {
  .time-settings {
    grid-template-columns: 1fr;
  }
  
  .preview-container {
    grid-template-columns: 1fr;
  }
  
  .customization-options {
    gap: 20px;
  }
  
  .option-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .slider-container {
    width: 100%;
    max-width: none;
  }
}

@media (max-width: 480px) {
  .theme-toggle-container {
    padding: 16px;
  }
  
  .mode-button {
    padding: 12px;
  }
  
  .auto-settings {
    padding: 16px;
  }
  
  .color-picker {
    flex-wrap: wrap;
  }
  
  .color-option {
    width: 32px;
    height: 32px;
  }
}
</style>